<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ETF基金行情列表</title>
    <!-- 引入axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.2/dist/axios.min.js"></script>
    
    <style>
        /* 全局样式 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* 标题样式 */
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
            font-size: 28px;
        }
        
        /* 工具栏样式 */
        .toolbar {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .search-bar {
            display: flex;
            gap: 10px;
            flex: 1;
            max-width: 400px;
        }
        
        .search-bar input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #45a049;
        }
        
        .btn-danger {
            background-color: #f44336;
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #da190b;
        }
        
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        /* 表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .data-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #333;
        }
        
        .data-table tbody tr:hover {
            background-color: #f5f5f5;
        }
        
        /* 涨跌颜色 */
        .positive {
            color: #f44336;
        }
        
        .negative {
            color: #4CAF50;
        }
        
        /* 分页控件 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            margin-top: 20px;
        }
        
        /* 加载、错误和空数据提示 */
        .loading,
        .error,
        .empty {
            padding: 40px;
            text-align: center;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .error {
            color: #f44336;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .toolbar {
                flex-direction: column;
                gap: 15px;
            }
            
            .search-bar {
                max-width: 100%;
                width: 100%;
            }
            
            .data-table {
                display: block;
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>ETF基金行情列表</h1>
        
        <div class="toolbar">
            <div class="search-bar">
                <input type="text" id="searchInput" placeholder="输入基金代码或名称搜索...">
                <button id="searchBtn" class="btn btn-primary">搜索</button>
            </div>
            <div class="action-buttons">
                <button id="fetchBtn" class="btn btn-primary">抓取最新数据</button>
                <button id="clearBtn" class="btn btn-danger">清空数据</button>
            </div>
        </div>
        
        <!-- 加载状态 -->
        <div id="loading" class="loading">加载中...</div>
        
        <!-- 错误信息 -->
        <div id="error" class="error" style="display: none;"></div>
        
        <!-- 空数据提示 -->
        <div id="empty" class="empty" style="display: none;">暂无数据</div>
        
        <!-- 数据表格 -->
        <table id="etfTable" class="data-table" style="display: none;">
            <thead>
                <tr>
                    <th>基金代码</th>
                    <th>基金名称</th>
                    <th>最新价</th>
                    <th>涨跌额</th>
                    <th>涨跌幅</th>
                    <th>成交量(万)</th>
                    <th>成交额(亿)</th>
                    <th>开盘价</th>
                    <th>最高价</th>
                    <th>最低价</th>
                    <th>昨收价</th>
                </tr>
            </thead>
            <tbody id="etfTableBody">
                <!-- 数据将通过JavaScript动态填充 -->
            </tbody>
        </table>
        
        <!-- 分页控件 -->
        <div class="pagination">
            <button id="prevPage" class="btn">上一页</button>
            <span id="pageInfo">第 1 / 1 页</span>
            <button id="nextPage" class="btn">下一页</button>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        const pageSize = 20;
        let totalData = [];
        let filteredData = [];
        
        // 页面加载时获取数据
        window.onload = function() {
            loadETFData();
            
            // 绑定事件
            document.getElementById('fetchBtn').addEventListener('click', fetchETFData);
            document.getElementById('clearBtn').addEventListener('click', clearETFData);
            document.getElementById('searchBtn').addEventListener('click', searchETFData);
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchETFData();
                }
            });
            document.getElementById('prevPage').addEventListener('click', goToPrevPage);
            document.getElementById('nextPage').addEventListener('click', goToNextPage);
        };
        
        // 加载ETF数据
        function loadETFData() {
            showLoading();
            
            axios.get('/api/etf/list')
                .then(response => {
                    hideLoading();
                    if (response.data.success) {
                        totalData = response.data.data;
                        filteredData = [...totalData];
                        renderTable();
                        updatePagination();
                    } else {
                        showError('获取数据失败: ' + response.data.message);
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('获取数据异常: ' + (error.response ? error.response.data.message : error.message));
                });
        }
        
        // 抓取最新数据
        function fetchETFData() {
            showLoading();
            
            axios.post('/api/etf/fetch')
                .then(response => {
                    hideLoading();
                    if (response.data.success) {
                        alert('数据抓取成功，共获取 ' + response.data.data + ' 条记录');
                        loadETFData(); // 重新加载数据
                    } else {
                        alert('数据抓取失败: ' + response.data.message);
                    }
                })
                .catch(error => {
                    hideLoading();
                    alert('数据抓取异常: ' + (error.response ? error.response.data.message : error.message));
                });
        }
        
        // 清空数据
        function clearETFData() {
            if (confirm('确定要清空所有ETF数据吗？此操作不可撤销。')) {
                showLoading();
                
                axios.delete('/api/etf/clear')
                    .then(response => {
                        hideLoading();
                        if (response.data.success) {
                            alert('数据清空成功');
                            loadETFData(); // 重新加载数据
                        } else {
                            alert('数据清空失败: ' + response.data.message);
                        }
                    })
                    .catch(error => {
                        hideLoading();
                        alert('数据清空异常: ' + (error.response ? error.response.data.message : error.message));
                    });
            }
        }
        
        // 搜索ETF数据
        function searchETFData() {
            const keyword = document.getElementById('searchInput').value.trim().toLowerCase();
            if (keyword) {
                filteredData = totalData.filter(item => 
                    item.code.toLowerCase().includes(keyword) || 
                    item.name.toLowerCase().includes(keyword)
                );
            } else {
                filteredData = [...totalData];
            }
            currentPage = 1;
            renderTable();
            updatePagination();
        }
        
        // 渲染表格
        function renderTable() {
            const tableBody = document.getElementById('etfTableBody');
            tableBody.innerHTML = '';
            
            if (filteredData.length === 0) {
                document.getElementById('etfTable').style.display = 'none';
                document.getElementById('empty').style.display = 'block';
                return;
            }
            
            // 分页处理
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            const pageData = filteredData.slice(start, end);
            
            pageData.forEach(item => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${item.code}</td>
                    <td>${item.name}</td>
                    <td>${formatDecimal(item.latestPrice, 4)}</td>
                    <td class="${item.priceChange > 0 ? 'positive' : item.priceChange < 0 ? 'negative' : ''}">
                        ${formatDecimal(item.priceChange, 4)}
                    </td>
                    <td class="${item.changePercent > 0 ? 'positive' : item.changePercent < 0 ? 'negative' : ''}">
                        ${formatDecimal(item.changePercent, 2)}%
                    </td>
                    <td>${formatVolume(item.volume)}</td>
                    <td>${formatAmount(item.amount)}</td>
                    <td>${formatDecimal(item.openPrice, 4)}</td>
                    <td>${formatDecimal(item.highPrice, 4)}</td>
                    <td>${formatDecimal(item.lowPrice, 4)}</td>
                    <td>${formatDecimal(item.prevClosePrice, 4)}</td>
                `;
                tableBody.appendChild(row);
            });
            
            document.getElementById('etfTable').style.display = 'table';
            document.getElementById('empty').style.display = 'none';
        }
        
        // 更新分页信息
        function updatePagination() {
            const totalPages = Math.ceil(filteredData.length / pageSize);
            document.getElementById('pageInfo').textContent = `第 ${currentPage} / ${totalPages} 页`;
            
            document.getElementById('prevPage').disabled = currentPage === 1;
            document.getElementById('nextPage').disabled = currentPage === totalPages;
        }
        
        // 上一页
        function goToPrevPage() {
            if (currentPage > 1) {
                currentPage--;
                renderTable();
                updatePagination();
            }
        }
        
        // 下一页
        function goToNextPage() {
            const totalPages = Math.ceil(filteredData.length / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                renderTable();
                updatePagination();
            }
        }
        
        // 格式化小数
        function formatDecimal(value, digits) {
            if (value === null || value === undefined) return '-';
            return parseFloat(value).toFixed(digits);
        }
        
        // 格式化成交量（转换为万）
        function formatVolume(volume) {
            if (volume === null || volume === undefined) return '-';
            return (volume / 10000).toFixed(2);
        }
        
        // 格式化成交额（转换为亿）
        function formatAmount(amount) {
            if (amount === null || amount === undefined) return '-';
            return (amount / 100000000).toFixed(2);
        }
        
        // 显示加载状态
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            document.getElementById('etfTable').style.display = 'none';
            document.getElementById('empty').style.display = 'none';
        }
        
        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }
        
        // 显示错误信息
        function showError(message) {
            document.getElementById('error').textContent = message;
            document.getElementById('error').style.display = 'block';
        }
    </script>
</body>
</html>